package util;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalendarConvert {

	/**
	 * Convert a date string from database to a Calendar object
	 * 
	 * @param dateString The date from the database
	 * @throws IllegalArgumentException
	 * @return Calendar
	 */
	public static Calendar convertDateStringToCalendar(String dateString) {
		String[] splitDateString = dateString.split(" ");
		String[] splitDate = splitDateString[0].split("-");
		String[] splitTime = splitDateString[1].split(":");
		
		if(splitDateString.length == 2 && splitDate.length == 3 && (splitTime.length == 2 || splitTime.length == 3)) {
			return new GregorianCalendar(Integer.parseInt(splitDate[0]), Integer.parseInt(splitDate[1]) - 1, Integer.parseInt(splitDate[2]), Integer.parseInt(splitTime[0]), Integer.parseInt(splitTime[1]), 0);
		} else {
			throw new IllegalArgumentException(String.format("Date string is not in correct format {%1$s}", dateString));
		}
	}

	/**
	 * Convert a Calendar object to a date string
	 * 
	 * @param calendar The calendar object
	 * @return String
	 */
	public static String convertCalendarToDateString(Calendar calendar) {
		return String.format("%1$tY-%1$tm-%1$te %1$tH:%1$tM:%1$tS", calendar);
	}
	
	
	/**
	 * Check if 2 dates are equal, only check if year, month and day are the same.
	 * The compareTo method cannot be used because it also checks for hour, minute and second.
	 * 
	 * @param date1 First date to check
	 * @param date2 The date to compare to
	 * @return boolean
	 */
	public static boolean compareDates(Calendar date1, Calendar date2) {
		if(date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) && date1.get(Calendar.MONTH) == date2.get(Calendar.MONTH) && date1.get(Calendar.DAY_OF_MONTH) == date2.get(Calendar.DAY_OF_MONTH)) {
			return true;
		}

		return false;
	}
}
